package com.yhm.NIO.NIOSelector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {

  public static void main(String[] args) {

    try {
      SocketChannel socketChannel = SocketChannel.open();

      socketChannel.configureBlocking(false);//设置非阻塞
      socketChannel.connect(new InetSocketAddress("localhost", 8080));
      while (!socketChannel.finishConnect()) {

      }
      //写入数据
      ByteBuffer byteBuffer = ByteBuffer.wrap(("随机Math.random()" + Math.random() + "数据").getBytes());

      System.out.println("客户端发送数据大小="+byteBuffer.capacity());
      while ((byteBuffer.hasRemaining())) {
        socketChannel.write(byteBuffer);
      }

      //读取服务器返回
      ByteBuffer readBuffer = ByteBuffer.allocate(1024);
      while (socketChannel.isOpen() && (socketChannel.read(readBuffer) != -1)) {//循环判断 是否已经 读取到内容了
        if (readBuffer.position() > 0) {
          break;
        }
      }

      readBuffer.flip();//切换到读模式
      byte content[] = new byte[readBuffer.limit()];
      readBuffer.get(content);
      System.out.println("读取到了服务端返回的结果：" + new String(content));

      socketChannel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
}
